package com.atguigu.mall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.atguigu.common.constant.PmsConst;
import com.atguigu.common.page.PageFactory;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.mall.product.dao.AttrGroupDao;
import com.atguigu.mall.product.dto.AttrAttrgroupRelationDTO;
import com.atguigu.mall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.mall.product.entity.AttrEntity;
import com.atguigu.mall.product.entity.AttrGroupEntity;
import com.atguigu.mall.product.entity.CategoryEntity;
import com.atguigu.mall.product.service.AttrAttrgroupRelationService;
import com.atguigu.mall.product.service.AttrGroupService;
import com.atguigu.mall.product.service.AttrService;
import com.atguigu.mall.product.service.CategoryService;
import com.atguigu.mall.product.vo.AttrGroupRelTableVO;
import com.atguigu.mall.product.vo.AttrGroupWithAttrsVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Override
    public PageUtils queryPage(AttrGroupEntity attrGroup) {
        IPage<AttrGroupEntity> page = PageFactory.defaultPage();
        LambdaQueryWrapper<AttrGroupEntity> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(attrGroup)) {
            Long catelogId = attrGroup.getCatelogId();
            String attrGroupName = attrGroup.getAttrGroupName();
            wrapper.like(StrUtil.isNotBlank(attrGroupName), AttrGroupEntity::getAttrGroupName, attrGroupName);
            wrapper.eq(ObjectUtil.isNotNull(catelogId), AttrGroupEntity::getCatelogId, catelogId);
        }
        this.page(page, wrapper);
        List<AttrGroupEntity> records = page.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            records.forEach(item -> {
                String categoryName = "--";
                Long catelogId = item.getCatelogId();
                if (ObjectUtil.isNotNull(catelogId)) {
                    CategoryEntity categoryEntity = categoryService.getById(catelogId);
                    if (ObjectUtil.isNotNull(categoryEntity)) {
                        categoryName = categoryEntity.getName();
                    }
                }
                item.setCatelogName(categoryName);
            });
        }
        return new PageUtils(page);
    }

    @Override
    public List<AttrGroupEntity> queryListByParams(AttrGroupEntity attrGroup) {
        Long catelogId = attrGroup.getCatelogId();
        LambdaQueryWrapper<AttrGroupEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtil.isNotNull(catelogId), AttrGroupEntity::getCatelogId, catelogId);
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public PageUtils attrGroupRelationAttrList(Long attrGroupId, Map<String, Object> params) {
        params.put("attrGroupId", attrGroupId);
        Page<AttrGroupRelTableVO> page = PageFactory.defaultPage();
        List<AttrGroupRelTableVO> list = this.baseMapper.attrGroupRelationAttrList(page, params);
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public PageUtils attrGroupNotRelationAttrList(Long attrGroupId, Map<String, Object> params) {
        IPage<AttrEntity> page = PageFactory.defaultPage();
        AttrGroupEntity attrGroup = this.getById(attrGroupId);
        Long catelogId = attrGroup.getCatelogId();
        List<AttrGroupEntity> otherGroupList = this.queryOtherGroup(attrGroupId);
        /**
         * 1.查询出当前分组其他分组
         */
        List<Long> attrGroupIdList = otherGroupList.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());

        /**
         * 2. 查询出其他分组关联的属性 id
         */
        LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupIdList);
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(wrapper);
        List<Long> relationAttrIdList = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        /**
         * 3. 查询出
         */

        LambdaQueryWrapper<AttrEntity> pageWrapper = new LambdaQueryWrapper<>();
        pageWrapper.eq(AttrEntity::getCatelogId, catelogId);
        pageWrapper.eq(AttrEntity::getAttrType, PmsConst.ATTR_TYPE_BASE);
        String attrName = (String) params.get("attrName");
        if (StrUtil.isNotBlank(attrName)) {
            pageWrapper.like(AttrEntity::getAttrName, attrName);
        }
        if (CollUtil.isNotEmpty(relationAttrIdList)) {
            pageWrapper.notIn(AttrEntity::getAttrId, relationAttrIdList);
        }
        IPage<AttrEntity> pageObj = attrService.page(page, pageWrapper);
        /**
         * 查询当前所有关联属性、
         */
        return new PageUtils(pageObj);
    }

    @Override
    public List<AttrGroupEntity> queryOtherGroup(Long attrGroupId) {
        AttrGroupEntity attrGroup = this.getById(attrGroupId);
        Long catelogId = attrGroup.getCatelogId();
        LambdaQueryWrapper<AttrGroupEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttrGroupEntity::getCatelogId, catelogId);
        return this.list(wrapper);
    }

    @Override
    public void addRelation(AttrAttrgroupRelationDTO attrAttrgroupRelationDTO) {

        List<Long> attrIds = attrAttrgroupRelationDTO.getAttrIds();
        Long attrGroupId = attrAttrgroupRelationDTO.getAttrGroupId();
        if (CollUtil.isNotEmpty(attrIds)){
            List<AttrAttrgroupRelationEntity> newRelation = attrIds.stream().map(attrId -> AttrAttrgroupRelationEntity.builder().attrId(attrId)
                    .attrGroupId(attrGroupId).build()).collect(Collectors.toList());
            attrAttrgroupRelationService.saveBatch(newRelation);
        }

    }

    @Override
    public void removeAttrGroupByIds(List<Long> ids) {
        LambdaQueryWrapper<AttrGroupEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AttrGroupEntity::getAttrGroupId,ids);
        this.remove(wrapper);
        /**
         * 删除关联关系
         */
        attrAttrgroupRelationService.deleteByGroupIds(ids);
    }

    @Override
    public List<AttrGroupWithAttrsVO> withattr(Long catelogId) {
        AttrGroupEntity params = new AttrGroupEntity();
        params.setCatelogId(catelogId);
        /**
         * 查询分类 关联的所有分组
         */
        List<AttrGroupEntity> groupList = this.queryListByParams(params);
        if (CollUtil.isNotEmpty(groupList)){
            List<Long> groupIds = groupList.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());


            /**
             * 查询分类下的属性
             */
            List<AttrEntity> attrList = this.attrService.queryListByCategoryId(catelogId);
            /**
             * 查询关联关系
              */
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.queryRelByGroupIds(groupIds);
            List<AttrGroupWithAttrsVO> groupWithAttrsVOList = groupList.stream().map(item -> {

                /**
                 * 1.copy 原有属性
                 */
                AttrGroupWithAttrsVO attrGroupWithAttrsVO = new AttrGroupWithAttrsVO();
                BeanUtil.copyProperties(item, attrGroupWithAttrsVO);

                /**
                 * 2.分组关联对应属性
                 */
                Long attrGroupId = item.getAttrGroupId();
                if (CollUtil.isNotEmpty(relationEntities)){
                    List<Long> relAttrIds = relationEntities.stream()
                            .filter(rel -> rel.getAttrGroupId().equals(attrGroupId))
                            .map(AttrAttrgroupRelationEntity::getAttrId)
                            .collect(Collectors.toList());

                    if (CollUtil.isNotEmpty(relAttrIds)){
                        List<AttrEntity> groupAttrList = attrList.stream().filter(attr -> relAttrIds.contains(attr.getAttrId())).collect(Collectors.toList());
                        attrGroupWithAttrsVO.setAttrs(groupAttrList);
                    }

                }
                return attrGroupWithAttrsVO;
            }).collect(Collectors.toList());
            return  groupWithAttrsVOList;
        }
        return new ArrayList<>();
    }
}